import {
  CloseCircleOutlined,
  PaperClipOutlined,
  UploadOutlined,
} from "@ant-design/icons";
import { AutoFocusPlugin } from '@lexical/react/LexicalAutoFocusPlugin';
import { LexicalComposer } from '@lexical/react/LexicalComposer';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { ContentEditable } from '@lexical/react/LexicalContentEditable';
import LexicalErrorBoundary from '@lexical/react/LexicalErrorBoundary';
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';
import { $createTextNode, $getRoot } from 'lexical';
import { $createHeadingNode } from '@lexical/rich-text';
import { GlyfEditor } from 'glyf';


import { Button, Collapse, Modal, Upload, message } from "antd";
import { UploadChangeParam } from "antd/es/upload";
import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  DeleteSubmission,
  GetQuestions,
  GetSubmission,
  UPLOAD_PATH,
} from "../../../api";
import { SidebarStudent } from "../../../components/Sidebar";
import { Question, Submission } from "../../../utils/constant";
import "./index.less";

const { Panel } = Collapse;

const Index: React.FC = () => {
  const [questions, setQuestions] = useState<Question[]>([]);
  const [submissonList, setSubmissionList] = useState<Submission[]>([]);
  const params = useParams();
  const moduleId = +params.id!;
  const assignmentId = +params.assignmentId!;
  const studentId = window.localStorage.getItem("userId");

  const navigate = useNavigate();

  const fetchQuestionList = async () => {
    try {
      const res = await GetQuestions({ assignmentId });
      const { code, msg } = res;
      if (code !== "00000") {
        throw new Error(msg);
      }
      setQuestions(res.data);
    } catch (e: any) {
      console.error(e);
      message.error(e);
    }
  };

  const fetchSubmission = async () => {
    try {
      const { data, code, msg } = await GetSubmission({ assignmentId });
      if (code !== "00000" || data === null) {
        setSubmissionList([]);
        throw new Error(msg);
      }
      setSubmissionList([data]);
    } catch (e) {
      console.error(e);
    }
  };

  const handleUpload = (options: UploadChangeParam) => {
    try {
      console.log({ options });
      const {
        file: { response },
      } = options;
      if (response) {
        const { code, msg, data } = response;
        if (code !== "00000") {
          throw new Error(msg);
        }
        message.success("Submit Success");
        setSubmissionList((list) => [...list, data]);
      }
    } catch (e) {
      message.error(`Submit Error! (${e})`);
      console.error(e);
    }
  };

  const deleteConfirm = (id: number) => {
    Modal.confirm({
      title: "Are you sure to delete?",
      okText: "Yes",
      cancelText: "Cancel",
      onOk: () => {
        handleDeleteSubmission(id);
      },
    });
  };

  const handleDeleteSubmission = async (id: number) => {
    try {
      await DeleteSubmission({ ids: [id] });
      await fetchSubmission();
    } catch (e) {
      console.error(e);
    }
  };

  useEffect(() => {
    fetchQuestionList();
    fetchSubmission();
  }, []);


  const theme = {
    heading:{
      h1:'glyf-editor-h1'
    },
    text:{
      bold:'glyf-editor-bold',
      italic:'glyf-editor-italic'
    }
  }
  function onError(error: any) {
    console.error(error);
  }
  const initialConfig = {
    namespace: 'MyEditor',
    theme,
    onError,
  };
  
  function MyHeadingPlugin(): JSX.Element {
      const [editor]=useLexicalComposerContext();
      const onClick =(e: React.MouseEvent): void => {
          editor.update(()=>{
              const root = $getRoot();
              root.append($createHeadingNode('h1').append($createTextNode( "Hello world")));
          });
      };
      return <button onClick={onClick}>Heading</button>;
  }

  return (
      <>
        <SidebarStudent />
        <div className="student-question-list">
          <div className="student-question-list-header">
            <Button
                onClick={() => {
                  navigate(`/student/assignment/${assignmentId}/grading`);
                }}
            >
              Grading Tasks
            </Button>
            <Button
                onClick={() => {
                  navigate(`/student/assignment/${assignmentId}/viewFeedback`);
                }}
            >
              View Feedback
            </Button>
          </div>
          <Collapse className="student-question-card">
            {questions.map((item, index) => (
                <Panel header={`Question ${index + 1}`} key={item.id}>
                  <p>{item.questionText}</p>
                </Panel>
            ))}
          </Collapse>
          <div className="uploader-wrapper">
            <Upload
                onChange={handleUpload}
                showUploadList={false}
                className="uploader"
                action={UPLOAD_PATH}
                data={{
                  studentId,
                  moduleId,
                  assignmentId,
                }}
            >
              <Button icon={<UploadOutlined />}>Submit</Button>
            </Upload>
            {submissonList.map((item) => (
                <div key={item.id} className="submission-card">
                  <PaperClipOutlined></PaperClipOutlined>
                  <div className="name">file.pdf</div>
                  <CloseCircleOutlined
                      className="delete-btn"
                      onClick={() => {
                        deleteConfirm(item.id);
                      }}
                  ></CloseCircleOutlined>
                </div>
            ))}
          </div>
          <div >
            <LexicalComposer initialConfig={initialConfig}>
              <MyHeadingPlugin/>
              <RichTextPlugin
                  contentEditable={<ContentEditable className="contentEditable"/>}
                  placeholder={<div>Enter some texts...</div>}
                  ErrorBoundary={LexicalErrorBoundary}
              />
              <AutoFocusPlugin />
            </LexicalComposer>
          </div>
          <div>
            {/* <GlyfEditor/> */}
          </div>
        </div>
      </>
  );
};

export default Index;
